package jh.jianguan.springboot.service.common.impl;

import jh.jianguan.springboot.dao.UserMapper;
import jh.jianguan.springboot.dto.common.security.SecurityRole;
import jh.jianguan.springboot.dto.common.security.SecurityUserDetails;
import jh.jianguan.springboot.model.User;
import jh.jianguan.springboot.service.common.ISecurityUserDetailsService;
import jh.jianguan.springboot.util.common.exception.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: guoc
 * @createDate: 2020/11/30 15:06
 */
@Primary
@Slf4j
@Service
public class SecurityUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    /**
     * 自定义安全模块的用户认证
     * @return org.springframework.security.core.userdetails.UserDetails
     * @author guoc
     * @date 2020/11/30 14:45
     */
    @Override
    public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException  {
            User sysUserEntity = userMapper.selectByUserName(username);
            if (null!=sysUserEntity){
               log.info("自定义安全模块的用户认证"+sysUserEntity.getUserName());
                /**
                 * 自定义安全框架用户注册，可修改为数据库查询
                 * @author guoc
                 * @date 2020/12/2 13:22
                 */
                SecurityRole role=new SecurityRole(1,"admin","系统管理员");
                SecurityRole role2=new SecurityRole(2,"user","用户");
                List<SecurityRole> roles =new ArrayList<>();
                roles.add(role);
                roles.add(role2);

                SecurityUserDetails userDetails=
                        new SecurityUserDetails(sysUserEntity.getId(),sysUserEntity.getUserName(),new BCryptPasswordEncoder().encode(sysUserEntity.getPassWord()),true,false,roles);

                return userDetails;

            }
            throw  ExceptionUtil.mxe(username+".这个用户不存在");
        }
}
